package com.ruoyi.web.controller.kpl.other;

import okhttp3.*;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.charset.Charset;
import java.util.Objects;

public class LonghuApiClient {

    private final OkHttpClient client;

    public LonghuApiClient() {
        this.client = new OkHttpClient();
    }

    public void makeRequest() {
        HttpUrl url = new HttpUrl.Builder()
                .scheme("https")
                .host("apphq.longhuvip.com")
                .addPathSegment("w1")
                .addPathSegment("api")
                .addPathSegment("index.php")
                .addQueryParameter("Order", "1")
                .addQueryParameter("a", "RealRankingInfo")
                .addQueryParameter("st", "30")
                .addQueryParameter("apiv", "w21")
                .addQueryParameter("Type", "1")
                .addQueryParameter("c", "ZhiShuRanking")
                .addQueryParameter("PhoneOSNew", "1")
                .addQueryParameter("ZSType", "7")
                .build();

        Request request = new Request.Builder()
                .url(url)
                .header("Accept", "*/*")
                .header("Accept-Encoding", "gzip") // 只保留 gzip，避免多种编码
                .header("Accept-Language", "zh-CN,zh;q=0.9")
                .header("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36")
                .get()
                .build();

        try (Response response = client.newCall(request).execute()) {
            if (response.isSuccessful()) {
                // 方法1: 使用正确的字符编码
                ResponseBody body = response.body();
                if (body != null) {
                    // 获取响应内容类型，确定字符集
                    MediaType contentType = body.contentType();
                    Charset charset = contentType != null ? contentType.charset(StandardCharsets.UTF_8) : StandardCharsets.UTF_8;

                    String responseBody = new String(body.bytes(), charset);
                    System.out.println("请求成功!");
                    System.out.println("响应状态: " + response.code());
                    System.out.println("字符集: " + charset);
                    System.out.println("响应内容: " + responseBody);

                    // 也可以将响应保存到文件查看
                    // saveToFile(responseBody, "response.json");
                }
            } else {
                System.out.println("请求失败! 状态码: " + response.code());
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    // 方法2: 手动处理GZIP压缩（如果自动解压失败）
    public void makeRequestWithManualGzip() {
        OkHttpClient clientWithManualGzip = new OkHttpClient.Builder()
                .addInterceptor(chain -> {
                    Request originalRequest = chain.request();
                    Request compressedRequest = originalRequest.newBuilder()
                            .header("Accept-Encoding", "gzip")
                            .build();

                    Response response = chain.proceed(compressedRequest);

                    // 如果响应是gzip压缩的，手动解压
                    if (Objects.equals(response.header("Content-Encoding"), "gzip")) {
                        String body = response.body().string();
                        return response.newBuilder()
                                .body(ResponseBody.create(body, response.body().contentType()))
                                .removeHeader("Content-Encoding")
                                .build();
                    }

                    return response;
                })
                .build();

        HttpUrl url = new HttpUrl.Builder()
                .scheme("https")
                .host("apphq.longhuvip.com")
                .addPathSegment("w1")
                .addPathSegment("api")
                .addPathSegment("index.php")
                .addQueryParameter("Order", "1")
                .addQueryParameter("a", "RealRankingInfo")
                .addQueryParameter("st", "30")
                .addQueryParameter("apiv", "w21")
                .addQueryParameter("Type", "1")
                .addQueryParameter("c", "ZhiShuRanking")
                .addQueryParameter("PhoneOSNew", "1")
                .addQueryParameter("ZSType", "7")
                .build();

        Request request = new Request.Builder()
                .url(url)
                .header("Accept", "*/*")
                .header("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36")
                .get()
                .build();

        try (Response response = clientWithManualGzip.newCall(request).execute()) {
            if (response.isSuccessful()) {
                String responseBody = response.body().string();
                System.out.println("手动GZIP处理 - 请求成功!");
                System.out.println("响应内容: " + responseBody);
            } else {
                System.out.println("请求失败! 状态码: " + response.code());
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    // 方法3: 尝试不同的字符编码
    public void tryDifferentCharsets(byte[] responseBytes) {
        Charset[] charsets = {
                StandardCharsets.UTF_8,
                Charset.forName("GBK"),
                Charset.forName("GB2312"),
                Charset.forName("ISO-8859-1"),
                StandardCharsets.US_ASCII
        };

        for (Charset charset : charsets) {
            try {
                String decoded = new String(responseBytes, charset);
                System.out.println("尝试字符集 " + charset.name() + ": " + decoded.substring(0, Math.min(100, decoded.length())));
            } catch (Exception e) {
                System.out.println("字符集 " + charset.name() + " 解码失败");
            }
        }
    }

    // 保存响应到文件
    private void saveToFile(String content, String filename) {
        try {
            java.nio.file.Files.write(
                    java.nio.file.Paths.get(filename),
                    content.getBytes(StandardCharsets.UTF_8)
            );
            System.out.println("响应已保存到: " + filename);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        LonghuApiClient client = new LonghuApiClient();

        System.out.println("=== 标准请求 ===");
        client.makeRequest();

        System.out.println("\n=== 手动GZIP处理 ===");
        client.makeRequestWithManualGzip();
    }


}